package org.ccu.eshop.utils;


import com.alibaba.fastjson.JSON;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


/**
 * 用户登录拦截器  认证用户是否登录
 */
@WebFilter("/api/auth/*")
public class UserIsLoginFilterUtil implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //在session中找用户登录信息  如果存在登录信息，就让其通过，否则，就返回一个AjaxResult对象   code =505
        HttpServletRequest request=(HttpServletRequest)servletRequest;
        HttpServletResponse response=(HttpServletResponse)servletResponse;
        HttpSession session =request.getSession();
        if(session!=null){
            Object obj=session.getAttribute("loginMember");
            if(obj!=null){
                filterChain.doFilter(servletRequest,servletResponse);
            }else{
                AjaxResultUtil result=AjaxResultUtil.error(505,"用户未登录-");
                response.getWriter().write(JSON.toJSONString(result));
            }
        }else{
            AjaxResultUtil result=AjaxResultUtil.error(506,"session不存在-");
            response.getWriter().write(JSON.toJSONString(result));
        }


    }


    @Override
    public void destroy() {

    }
}
